In React, inline handlers let you execute functions directly inside JSX. This is especially useful when you need to pass arguments to a function, such as removing a specific item from a list.
First, define the list as a stateful value so it can be updated:
const [stories, setStories] = React.useState(initialStories);Then define a function to remove items:
const handleRemoveStory = (item) => {
const newStories = stories.filter(
(story) => item.objectID !== story.objectID
);
setStories(newStories);
};Pass handleRemoveStory to the List component:
<List list={searchedStories} onRemoveItem={handleRemoveStory} />Then use it in the Item component.
Normally, you’d define a local function first:
const handleRemoveItem = () => {
onRemoveItem(item);
};And attach it to the button:
<button onClick={handleRemoveItem}>Dismiss</button>To simplify, use an inline arrow function:
<button onClick={() => onRemoveItem(item)}>Dismiss</button>Or use bind:
<button onClick={onRemoveItem.bind(null, item)}>Dismiss</button>Inline handlers in JSX offer a clean way to execute functions with arguments. They simplify code, especially for tasks like removing items from a list. However, when logic grows, it’s better to extract handlers for clarity and maintainability.